package main

import (
	"context"
	"encoding/json"
	"gin_study_blog/common"
	"gin_study_blog/core"
	"gin_study_blog/models"
	"gin_study_blog/service/redis"
	"github.com/olivere/elastic/v7"
	"github.com/sirupsen/logrus"
)

func main() {
	// 读取配置文件
	core.YamlInitConfig()
	// 初始化日志
	common.Log = core.InitLogger()
	// redis 初始化
	common.Redis = core.ConnectRedis()
	// 连接 es
	common.EsClient = core.EsConnect()

	result, err := common.EsClient.Search(models.ArticleModel{}.Index()).
		Query(elastic.NewMatchAllQuery()).
		Do(context.Background())

	if err != nil {
		logrus.Error(err)
		return
	}
	//utils.Digg("Ia4tM4sBU05yn7jzsXMm")
	diggInfo := redis.NewDigg().GetInfoAll()
	//utils.GetDiggInfo()
	//lookInfo := utils.GetArticleLookInfo()
	lookInfo := redis.NewArticleLook().GetInfoAll()
	for _, hit := range result.Hits.Hits {
		var article models.ArticleModel
		err = json.Unmarshal(hit.Source, &article)

		digg := diggInfo[hit.Id]
		look := lookInfo[hit.Id]
		newDig := article.LikeCount + digg
		newLook := article.LookCount + look
		if article.LikeCount == newDig && article.LookCount == newLook {
			logrus.Info(article.Title, "点赞数和浏览数无变化")
			continue
		}
		_, err = common.EsClient.Update().Index(models.ArticleModel{}.Index()).
			Id(hit.Id).
			Doc(map[string]int{
				"like_count": newDig,
				"look_count": newLook,
			}).
			Do(context.Background())
		if err != nil {
			logrus.Error(err)
			continue
		}
		logrus.Infof("%s, 数同步成功, 点赞数 %d 浏览数 %d", article.Title, newDig, newLook)
	}
	redis.NewDigg().Clear()
	redis.NewArticleLook().Clear()
}
